//
//  TicketView.m
//  pa
//
//  Created by HaiJiao Chen on 12-7-28.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "TicketView.h"
#import "AppDelegate.h"
#import "TicketList.h"
#import "MainObject.h"
#import "AddWaterView.h"
#import "nibLoader.h"
#import "TicketViewBG.h"
#import "KXUIColor.h"
#import "MapView.h"
#import "ImageDownloader.h"
#import "BatchWeightView.h"
#import "FilePack.h"
#import "text_def.h"

@interface TicketProduct : ListController
@end

@interface TicketProductDataSource:NSObject <DataSource>
-(void)setData:(NSArray*)data;
@end

@implementation TicketView
@synthesize ticketView;
@synthesize ticketBGView;
@synthesize logo;
@synthesize add_water_by;
@synthesize add_water_gal;
@synthesize time_left_plant;
@synthesize time_arrived_job;
@synthesize time_start_pour;
@synthesize time_finished_pour;
@synthesize time_left_job;
@synthesize time_arrived_plant;
@synthesize time_elapsed;
@synthesize date;
@synthesize trunk_no;
@synthesize driver;
@synthesize slump;
@synthesize plant_code;
@synthesize ticker_number;
@synthesize job_no;
@synthesize PO_no;
@synthesize account_no;
@synthesize project_no;
@synthesize address;
@synthesize sold_to;
@synthesize table;
@synthesize remarks;
@synthesize total_ordered;
@synthesize yards_today;
@synthesize allowable_time;
@synthesize sub_total;
@synthesize red_by;
@synthesize collect_grand_total;
@synthesize tax;
@synthesize total;
@synthesize batch_weight;
@synthesize slip_no;
@synthesize accpet;
@synthesize note;
@synthesize sign;

@synthesize map;
@synthesize scroll;

- (void)initlize
{
    timer = [KXTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(time) forMode:NSRunLoopCommonModes];
    product = [[TicketProduct alloc] init];
    productDatasource = [[TicketProductDataSource alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataSourceChanged:) name:DataSourceChangeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(imageDownload:) name:ImageDownloaderNotification object:nil];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self initlize];
    }
    return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [self initlize];
    }
    return self;
}
- (void)dealloc
{
    [timer invalidate];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [product release];
    [productDatasource release];
    [batchWeight release];
    [batchWeightDatasource release];
    [super dealloc];
}

- (IBAction)modify:(id)sender
{
    AddWaterView* v = [nibLoader load:@"AddWater" params:[NSNumber numberWithLongLong:self.ticketID]];
    [[AppDelegate sharedInstance].mainView addSubview:v];
}
- (IBAction)accept:(id)sender
{
    
}

- (IBAction)showBatchWeight:(id)sender
{
    NSMutableDictionary* c = [[AppDelegate sharedInstance].main.ticketsDataSource.memoryObject objectForKey:[NSString stringWithFormat:@"%lld", self.ticketID]];
    
    NSString* txt = [c valueForKey:BATCH_WEIGHT];
    if (txt && [[c valueForKey:HIDE_BATCH_WEIGHT] intValue] == 0)
    {
        UIView* view = [nibLoader load:@"DetailInformation" params:txt];
        [[[AppDelegate sharedInstance] window] addSubview:view];
    }
    //NSArray* arr = [c valueForKey:BATCH_WEIGHT];
    //if (arr)
    //{
    //    BatchWeightView* view = [nibLoader load:@"BatchWeight" params:nil];
    //    [view setData:arr];
    //    [[[AppDelegate sharedInstance] window] addSubview:view];
    //}
}

- (IBAction)showRemark:(id)sender
{
    UIView* view = [nibLoader load:@"DetailInformation" params:remarks.text];
    [[[AppDelegate sharedInstance] window] addSubview:view];
}

- (IBAction)showNote:(id)sender
{
    UIView* view = [nibLoader load:@"DetailInformation" params:note.text];
    [[[AppDelegate sharedInstance] window] addSubview:view];
}

@synthesize ticketID;
- (void)_dataSourceChanged
{
    TicketList* list = [AppDelegate sharedInstance].main.ticketsDataSource;
    NSArray* arr = list.data;
    NSDictionary* dic = nil;
    for (NSDictionary* ticket in arr)
    {
        if ([[ticket valueForKey:@"TicketID"] longLongValue] == ticketID)
        {
            dic = ticket;
        }
    }
    
    productDatasource.data = [dic valueForKey:@"Products"];            
    
    date.text = [dic valueForKey:@"Date"];
    trunk_no.text = [dic valueForKey:@"Truck_"];
    //driver.text = [dic valueForKey:@"DriverName"];
    slump.text = [dic valueForKey:@"Slump"];
    plant_code.text = [dic valueForKey:@"PlantID"];
    ticker_number.text = [dic valueForKey:@"Ticket_"];
    //job_no.text = [dic valueForKey:@"Admix_CustomerJobNumber"];
    PO_no.text = [dic valueForKey:@"PurchaseOrderNum"];
    account_no.text = [dic valueForKey:@"CustomerID"];
    //project_no.text = [dic valueForKey:@"ProjectNumber"];
    
    
    NSString* address1 = [dic valueForKey:@"DeliveryAddress1"];
    NSString* address2 = [dic valueForKey:@"DeliveryAddress2"];
    if (address1 == nil) address1 = @"";
    if (address2 == nil) address2 = @"";
    address.text = [NSString stringWithFormat:@"%@\n%@", address1, address2];
    
    
    
    
//    NSString* Shiptocustomeraddress1 = [dic valueForKey:@"Shiptocustomeraddress1"];
//    NSString* Shiptocustomercity = [dic valueForKey:@"Shiptocustomercity"];
//    NSString* Shiptocustomercod = [dic valueForKey:@"Shiptocustomercod"];
//    NSString* Shiptocustomername = [dic valueForKey:@"Shiptocustomername"];
//    NSString* Shiptocustomerpostalcd = [dic valueForKey:@"Shiptocustomerpostalcd"];
//    if (Shiptocustomeraddress1 == nil) Shiptocustomeraddress1 = @"";
//    if (Shiptocustomercity == nil) Shiptocustomercity = @"";
//    if (Shiptocustomercod == nil) Shiptocustomercod = @"";
//    if (Shiptocustomername == nil) Shiptocustomername = @"";
//    if (Shiptocustomerpostalcd == nil) Shiptocustomerpostalcd = @"";
//
//    sold_to.text = [NSString stringWithFormat:@"%@\n%@\n%@\n%@\n%@", Shiptocustomeraddress1, Shiptocustomercity, Shiptocustomercod, Shiptocustomername, Shiptocustomerpostalcd];

    NSString* CustomerName_1 = [dic valueForKey:@"CustomerName_1"];
    NSString* CustomerName_2 = [dic valueForKey:@"CustomerName_2"];
    NSString* CustomerName_3 = [dic valueForKey:@"CustomerName_3"];
    if (CustomerName_1 == nil) CustomerName_1 = @"";
    if (CustomerName_2 == nil) CustomerName_2 = @"";
    if (CustomerName_3 == nil) CustomerName_3 = @"";
    
    sold_to.text = [NSString stringWithFormat:@"%@\n%@\n%@", CustomerName_1, CustomerName_2, CustomerName_3];
    
    
    
    NSMutableString* temp = [[NSMutableString alloc] initWithCapacity:10];
    NSString* instruct = [dic valueForKey:@"DeliveryInstructions1"];
    if ([instruct length] > 0)
    {
        if ([temp length] > 0)
        {
            [temp appendString:@"\n"];
        }
        [temp appendString:instruct];
    }
    instruct = [dic valueForKey:@"DeliveryInstructions2"];
    if ([instruct length] > 0)
    {
        if ([temp length] > 0)
        {
            [temp appendString:@"\n"];
        }
        [temp appendString:instruct];
    }
    instruct = [dic valueForKey:@"DeliveryInstructions3"];
    if ([instruct length] > 0)
    {
        if ([temp length] > 0)
        {
            [temp appendString:@"\n"];
        }
        [temp appendString:instruct];
    }
    remarks.text = temp;
    [temp release];
    
    total_ordered.text = [dic valueForKey:@"OrderedQuantity"];
    yards_today.text = [dic valueForKey:@"CumulativeQuantity"];
    allowable_time.text = [dic valueForKey:@"TimeDueonJob"];
    float float_sub_total = [[dic valueForKey:@"Subtotal"] floatValue];
    float float_tax = [[dic valueForKey:@"Tax"] floatValue];
    float float_total = [[dic valueForKey:@"Total"] floatValue];
    if ([dic valueForKey:@"Subtotal"]) sub_total.text = [NSString stringWithFormat:@"%.2f", float_sub_total];
    if ([dic valueForKey:@"Tax"]) tax.text = [NSString stringWithFormat:@"%.2f", float_tax];
    if ([dic valueForKey:@"Total"]) total.text = [NSString stringWithFormat:@"%.2f", float_total];
    //sub_total.text = [dic valueForKey:@"Ticket Subtotal"];
    //tax.text = [dic valueForKey:@"Ticket Tax Total"];
    //@property (nonatomic, assign) IBOutlet UILabel* total;   sub total+tax
    //red_by.text= [dic valueForKey:@"red_by"];
    //collect_grand_total.text = [dic valueForKey:@"Ticket Grand Total"];
    
    
    
    NSDictionary* custom = [list.memoryObject objectForKey:[NSString stringWithFormat:@"%lld", ticketID]];
    [map setMap:[dic valueForKey:@"chj_address"] withPlat:[custom valueForKey:PLANT_ADDR]];
    add_water_by.text = [custom valueForKey:SIGN_NAME];
    add_water_gal.text = [custom valueForKey:ADD_WATER_GAL];
    
    time_left_plant.text = [custom valueForKey:STR_TIME_LEFT_PLANT];
    time_arrived_job.text = [custom valueForKey:STR_TIME_ARRIVED_JOB];
    time_start_pour.text = [custom valueForKey:STR_TIME_START_POUR];
    time_finished_pour.text = [custom valueForKey:STR_TIME_FINISHED_POUR];
    time_left_job.text = [custom valueForKey:STR_TIME_LEFT_JOB];
    time_arrived_plant.text = [custom valueForKey:STR_TIME_ARRIVED_PLANT];
    time_elapsed.text = [custom valueForKey:STR_TIME_ELAPSED];
    if ([[custom valueForKey:ACCEPT_TERMS] boolValue])
    {
        accpet.image = [UIImage imageNamed:@"check.png"];
    }
    else
    {
        accpet.image = [UIImage imageNamed:@"uncheck.png"];
    }
    note.text = [custom valueForKey:DRIVER_NOTE];
    
    if ([custom valueForKey:BATCH_WEIGHT] != nil && [[custom valueForKey:HIDE_BATCH_WEIGHT] intValue] == 0)
    {
        [batch_weight setTitle:[FilePack getStringByID:STR_BATCH_WEIGHT] forState:UIControlStateNormal];
    }
    else
    {
        [batch_weight setTitle:nil forState:UIControlStateNormal];
    }

    logo.image = [[ImageDownloader sharedInstance] downloadImage:[custom valueForKey:LOGO_URL]];
    

    NSArray* temp_arr = [custom valueForKey:SIGNATURE];
    if (temp_arr.count > 0)
    {
        sign.image = [temp_arr objectAtIndex:0];
    }
    else
    {
        sign.image = nil;
    }
}
- (void)dataSourceChanged:(NSNotification*)notification
{
    TicketList* list = [AppDelegate sharedInstance].main.ticketsDataSource;
    if ([notification object] == list)
    {
        NSDictionary* userInfo = [notification userInfo];
        NSArray* changed = [userInfo valueForKey:@"changed"];
        NSNumber* number = [NSNumber numberWithLongLong:ticketID];
        if ([changed indexOfObject:number] != -1)
        {
            [self _dataSourceChanged];
        }
    }
}

- (void)imageDownload:(NSNotification*)notification
{
    TicketList* list = [AppDelegate sharedInstance].main.ticketsDataSource;
    NSDictionary* custom = [list.memoryObject objectForKey:[NSString stringWithFormat:@"%lld", ticketID]];
    
    if ([[custom valueForKey:LOGO_URL] isEqual:[notification object]])
    {
        logo.image = [[ImageDownloader sharedInstance] downloadImage:[notification object]];
    }
}

- (void)setTicketID:(long long)_ticketID
{
    if (ticketID != _ticketID)
    {
        ticketID = _ticketID;
        [self _dataSourceChanged];
        [product setupController:table data:productDatasource reuse:@"items"];
    }
}

- (void)setupBG
{
    ticketBGView.image = [UIImage imageNamed:[NSString stringWithFormat:@"ticketbg_%@.png", [FilePack currentlanguage]]];
    [product setupController:table data:productDatasource reuse:@"items"];
    TicketViewBG* bg = [[TicketViewBG alloc] initWithFrame:CGRectZero];
    [product setBGWithColor1:[UIColor colorWithARGB:0xFFF7F7F7] color2:[UIColor colorWithARGB:0xFFC4CCD6] height:20 bg:bg];
    [bg release];
    scroll.contentSize = CGSizeMake(self.frame.size.width*2, self.frame.size.height);
}

-(void)time
{
    if ([trunk_no isHidden])
    {
        [trunk_no setHidden:NO];
    }
    else
    {
        [trunk_no setHidden:YES];
    }
}        


@end

@implementation TicketProduct

-(void)createSubView:(UITableViewCell*)cell
{
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 100, 20)];
    [cell.contentView addSubview:label];
    label.backgroundColor = [UIColor clearColor];
    label.tag = 1;
    [label release];
    
    label = [[UILabel alloc] initWithFrame:CGRectMake(110, 0, 436, 20)];
    [cell.contentView addSubview:label];
    label.backgroundColor = [UIColor clearColor];
    label.tag = 2;
    [label release];
    
    label = [[UILabel alloc] initWithFrame:CGRectMake(552, 0, 48, 20)];
    [cell.contentView addSubview:label];
    label.backgroundColor = [UIColor clearColor];
    label.tag = 3;
    [label release];

    label = [[UILabel alloc] initWithFrame:CGRectMake(606, 0, 106, 20)];
    [cell.contentView addSubview:label];
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = UITextAlignmentRight;
    label.tag = 4;
    [label release];

    label = [[UILabel alloc] initWithFrame:CGRectMake(720, 0, 88, 20)];
    [cell.contentView addSubview:label];
    label.textAlignment = UITextAlignmentRight;
    label.backgroundColor = [UIColor clearColor];
    label.tag = 5;
    [label release];

    label = [[UILabel alloc] initWithFrame:CGRectMake(816, 0, 126, 20)];
    [cell.contentView addSubview:label];
    label.textAlignment = UITextAlignmentRight;
    label.backgroundColor = [UIColor clearColor];
    label.tag = 6;
    [label release];
    cell.contentView.backgroundColor = [UIColor clearColor];
}
-(void)setupNewCell:(UITableViewCell*)cell obj:(id<NSObject>)obj indexPath:(NSIndexPath*)indexPath
{
    NSDictionary* dic = (NSDictionary*)obj;
    UILabel* productNo = (UILabel*)[cell.contentView viewWithTag:1];
    UILabel* description = (UILabel*)[cell.contentView viewWithTag:2];
    UILabel* unit = (UILabel*)[cell.contentView viewWithTag:3];
    UILabel* quantity = (UILabel*)[cell.contentView viewWithTag:4];
    UILabel* price = (UILabel*)[cell.contentView viewWithTag:5];
    UILabel* amount = (UILabel*)[cell.contentView viewWithTag:6];

    productNo.text = [dic valueForKey:@"Productno"];
    description.text = [dic valueForKey:@"description"];
    unit.text = [dic valueForKey:@"unit"];
    quantity.text = [dic valueForKey:@"quantity"];
    price.text = [NSString stringWithFormat:@"%.2f", [[dic valueForKey:@"unitprice"] floatValue]];
    amount.text = [NSString stringWithFormat:@"%.2f", [[dic valueForKey:@"amount"] floatValue]];
}
- (CGFloat)heightForRowAtIndexPath:(NSIndexPath *)indexPath obj:(id<NSObject>)obj
{
    return 20;
}

@end

@implementation TicketProductDataSource
@synthesize data;
-(void)dealloc
{
    [data release];
    [super dealloc];
}
-(void)setData:(NSArray*)_data
{
    [_data retain];
    [data release];
    data = _data;
}


@end




